import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
// 初始化仓库
const store = new Vuex.Store({
    //要共享的数据 仓库数据
    state: {
        allSelected: true,
        telnum:"",
        shoppingcai: [
            {
                img: '1073264.jpg_80x87.jpg',
                content: "[礼品]一鹿(路)有你永生花小夜灯-永生花礼盒",
                price: "388",
                dgpri: "298",
                alltotal: 0,
                count: 1,
                bol: true,
            }
        ]
    },
    // 修改器
    mutations: {
        jia(state, index) {
            state.shoppingcai[index].count++;
            console.log(state);
            // state.shoppingcai[index].alltotal = state.shoppingcai[index].count * state.shoppingcai[index].dgpri
        },
        jian(state, index) {
            state.shoppingcai[index].count--
            console.log(state.shoppingcai[index].count);
            // console.log(index);
            if (state.shoppingcai[index].count <= 0) {
                state.shoppingcai[index].count = 1
            };
            state.shoppingcai[index].alltotal = state.shoppingcai[index].count * state.shoppingcai[index].dgpri
        },
        // 删除
        deleteRow(state, index) {
            state.shoppingcai.splice(index, 1)
        },
        // 加入购物车
        addCart(state, item) {
            let arr= [];
            state.shoppingcai = state.shoppingcai.map(el=>{
                if(el.content==item.content){
                    return {
                        ...el,
                        count:el.count += item.count
                    }
                }
                return el;
            })
            if(!state.shoppingcai.some(el=>el.content==item.content)){
                arr.push(item)
            }
            state.shoppingcai = arr.concat(state.shoppingcai)
            // // state.datas.push(item)
        }
    },
    // 对列表进行过滤并计数
    getters: {
        // 总计
        total: (state) => {
            let sum = 0
            state.shoppingcai.filter(item => {
                if (item.bol) {
                    sum += item.count * item.dgpri
                }
            })
            return sum
        },
        // shoppingcais: (state) => {
        //     return state.shoppingcai
        // },
        // 购物车数量
        count: (state) => {
            return state.shoppingcai.length
        },
    }
})
export { store } // 抛出对象